<?php
//快递
class App_Deliver extends Data_Base
{
    protected static $_allItems = array();
    
	//获取总额
    public static function getMoney($deliverId, $moneyGoods, $address)
    {
        $info = DB::select()
            ->from('tiyu_deliver_config')
            ->where('id', '=', $deliverId)
            ->execute()
            ->current();

        if (empty($info))
            return 0;

        return self::getMoneyFromConfig($info['ltMoneyFee'], $info['egtMoneyFee'], $info['money'], $moneyGoods);
    }

	//获取快递名称
    public static function getName ($deliverId)
    {
        if (empty(self::$_allItems))
        {
            self::$_allItems = self::load_all('tiyu_deliver_config');
        }

        $item = Arr::get(self::$_allItems, $deliverId);
        return Arr::get($item, 'name', '');
    }

	//获取快递列表
    public static function infoList($arrGoodsBuyInfo, $addressList)
    {
        $shopId = self::getShopIdFromGoods($arrGoodsBuyInfo);
        self::initShopDeliver($shopId);

        $goodsMoney = 0;
        foreach ($arrGoodsBuyInfo as $goods)
        {
            $goodsMoney += $goods['money']['money'];
        }

        $query = DB::select()
            ->from('tiyu_deliver_config')
            ->where('shopId', '=', $shopId)
            ->order_by('sort', 'asc')
            ->execute();

        $ret = array();
        foreach ($query as $rs)
        {
            $rs['goodsDeliverMoney'] = self::getMoneyFromConfig($rs['ltMoneyFee'], $rs['egtMoneyFee'], $rs['money'], $goodsMoney);
            $ret[] = $rs;
        }

        return $ret;
    }

    public static function remove ($nid)
    {
        $rows = DB::update('tiyu_deliver_config')
            ->set(array('status' => 0))
            ->where('id', '=', $nid)
            ->execute();

        return $rows > 0;
    }

    public static function initShopDeliver ($shopId)
    {
        $count = self::counts('tiyu_deliver_config', array(
            array('shopId', '=', $shopId),
            array('status', '=', 1)));

        if ($count > 0)
            return ;

        DB::insert('tiyu_deliver_config')
            ->columns(array('name', 'sort', 'shopId', 'ltMoneyFee', 'egtMoneyFee', 'money', 'status'))
            ->values (array('快递', 1, $shopId, 1000, 0, 0, 1))
            ->execute();
    }

    public static function getShopIdFromGoods($arrGoodsList)
    {
        foreach ($arrGoodsList as $goods)
        {
            return Arr::get($goods, 'shopId');
        }
    }

    public static function getMoneyFromConfig($ltMoney, $egtMoney, $money, $goodsMoney)
    {
        if ($goodsMoney >= $money)
            return $egtMoney;
        else
            return $ltMoney;
    }
}
